package eip.chapter5.messagefilter.impl;

import java.io.StringWriter;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.JiBXException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;

import eip.chapter5.messagefilter.DeclarationMessage;
import eip.chapter5.messagefilter.HotelDeclarationService;

public class HotelDeclarationServiceImpl implements HotelDeclarationService {

	public JmsTemplate jmsTemplate;
	public String destination;

	public void makeDeclaration(DeclarationMessage msg) {
		System.out.println("Sending declaration: " + msg + " to " + destination );
		jmsTemplate.send(destination,new DeclarationMessageCreator(msg));
	}
	
	private static class DeclarationMessageCreator implements MessageCreator {

		DeclarationMessage declarationMessage;
		
		public DeclarationMessageCreator(DeclarationMessage msg) {
			declarationMessage = msg;
		}
		
		public Message createMessage(Session session) throws JMSException {
			StringWriter xmlMessage = new StringWriter();
			try {
				IBindingFactory bfact = BindingDirectory.getFactory(DeclarationMessage.class);
				IMarshallingContext mctx = bfact.createMarshallingContext();
					mctx.marshalDocument(declarationMessage, "UTF-8", null, xmlMessage);
			} catch (JiBXException e) {
				throw new JMSException("Error creating message: " + e.getMessage());
			}
			return session.createTextMessage(xmlMessage.toString());
		}
		
	}
	
	//-----------------------------------------------
	// Simple getters and setters
	//-----------------------------------------------
	
	public String getDestination() {
		return destination;
	}

	public void setDestination(String destination) {
		this.destination = destination;
	}

	public JmsTemplate getJmsTemplate() {
		return jmsTemplate;
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}



}
